package com.masterclient.app.businessmodule.minemodule.address;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.bean.address.AddressBean;
import com.eoner.baselibrary.bean.address.AddressListBean;
import com.eoner.baselibrary.bean.address.City;
import com.eoner.baselibrary.bean.address.UpdateAddressBean;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.UtilCollection;
import com.masterclient.app.R;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.minemodule.address.contract.EditAddressContract;
import com.masterclient.app.businessmodule.minemodule.address.contract.EditAddressPresenter;
import com.suke.widget.SwitchButton;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;

/**
 * 作者：sean
 * 创建时间：2017/8/25 18:49
 * 功能说明：
 */

public class EditAddressActivity extends FCBusinessActivity<EditAddressPresenter> implements EditAddressContract.View {


    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_shr)
    TextView tvShr;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.rl_right)
    RelativeLayout rlRight;
    @BindView(R.id.tag_tel)
    TextView tagTel;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tag_area)
    TextView tagArea;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.ll_choose_area)
    LinearLayout llChooseArea;
    @BindView(R.id.et_address_detail)
    EditText etAddressDetail;
    @BindView(R.id.tag_default)
    TextView tagDefault;
    @BindView(R.id.switch_button)
    SwitchButton switchButton;


    private AddressBean.DataBean.ShItemsBean itemsBean;

    RxPermissions rxPermissions;
    private AddressSelectDialog dialog;

    String address1,address2,address3;
    private String username, usernumber;
    private String mPositon = "3";
    private String areaId;
    String address,uname,uphone;
    private String isPurchase = "0";

    @Override
    protected int requireGetLayoutId() {
        return R.layout.activity_add_new_address;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("编辑收货地址");
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        isPurchase  = getIntent().getStringExtra("isPurchase");

        itemsBean = (AddressBean.DataBean.ShItemsBean) getIntent().getSerializableExtra("bean");

        etName.setText(itemsBean.getSh_full_name());

        etAddressDetail.setText(itemsBean.getSh_address());
        etPhone.setText(itemsBean.getSh_mobile());

        tvArea.setText(itemsBean.getSh_province()+" "+itemsBean.getSh_city()+" "+itemsBean.getSh_area());
        tvArea.setTextColor(Color.parseColor("#141922"));
        rxPermissions = new RxPermissions(this);
        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if(isChecked){
                    itemsBean.setSh_is_default("1");
                }else {
                    itemsBean.setSh_is_default("0");
                }
            }
        });

        areaId = itemsBean.getSh_area_id();
        address = itemsBean.getSh_address();
        uname = itemsBean.getSh_full_name();
        uphone = itemsBean.getSh_mobile();
        if("1".equals(itemsBean.getSh_is_default())){
            switchButton.setChecked(true);
        }else {
            switchButton.setChecked(false);
        }
    }

    @Override
    protected void onPause() {
        hideSoftInput(etPhone);
        super.onPause();
    }

    @OnClick({R.id.rl_right,R.id.tv_area,R.id.ll_choose_area,R.id.tv_save}) void onClick(View view){
        switch (view.getId()){
            case R.id.rl_right:

                rxPermissions
                        .requestEach(Manifest.permission.READ_CONTACTS
                        )
                        .subscribe(permission -> { // will emit 2 Permission objects
                            if (permission.granted) {
                                // `permission.name` is granted !
                                startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), 0);
                            } else if (permission.shouldShowRequestPermissionRationale){
                                // Denied permission without ask never again
                            } else {
                                // Denied permission with ask never again
                                // Need to go to the settings
                            }
                        });

                break;
            case R.id.tv_area:
                openAreaDialog();
                break;
            case R.id.ll_choose_area:
                openAreaDialog();
                break;
            case R.id.tv_save:
                address = etAddressDetail.getText().toString().trim();
                uname  =etName.getText().toString().trim();
               uphone = etPhone.getText().toString().trim();
                if(TextUtils.isEmpty(address)){
                    showToast("地址不能为空");
                    return;
                }
                if(!UtilCollection.isAddress(address)){
                    showToast("收货地址只允许 中文 英文 数字 - # 空格 中英文括号！");
                    return;
                }
                if(TextUtils.isEmpty(areaId)){
                    showToast("请选择地区");
                    return;
                }
                if(TextUtils.isEmpty(uname)){
                    showToast("请填写收货人");
                    return;
                }
                if(!StringsUtils.isPhoneNum(uphone)){
                    showToast("手机号码格式错误");
                    return;
                }
                mPresenter.updateAddress(itemsBean.getSh_id(),areaId,address.replace(" ",""),itemsBean.getSh_is_default(),uname,uphone);
                break;
        }
    }


    private void openAreaDialog() {
        dialog = new AddressSelectDialog(mContext,isPurchase);
        dialog.setOnSelectListener(new AddressSelectDialog.OnSelectListener() {
            @Override
            public void onSelect(String position, String id,String address) {
                mPositon = position;
                mPresenter.getRegionList(id);
                if("4".equals(position)){
                    address1 = address;
                }else if("5".equals(position)){
                    address2 = address;
                }
            }

            @Override
            public void onSelected(String id,String name) {
                areaId = id;
                address3 = name;
                tvArea.setText(address1+" "+address2+" "+address3);
                dialog.dismiss();
            }
        });
        dialog.show();
        mPresenter.getRegionList("0");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                //申请授权，第一个参数为要申请用户授权的权限；第二个参数为requestCode 必须大于等于0，主要用于回调的时候检测，匹配特定的onRequestPermissionsResult。
                //可以从方法名requestPermissions以及第二个参数看出，是支持一次性申请多个权限的，系统会通过对话框逐一询问用户是否授权。
                getUserInfo(data);
            }else{
                //如果该版本低于6.0，或者该权限已被授予，它则可以继续读取联系人。
                getUserInfo(data);
            }
        }
    }

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void getUserInfo(Intent data) {
        // ContentProvider展示数据类似一个单个数据库表
        // ContentResolver实例带的方法可实现找到指定的ContentProvider并获取到ContentProvider的数据
        ContentResolver reContentResolverol = getContentResolver();
        // URI,每个ContentProvider定义一个唯一的公开的URI,用于指定到它的数据集
        Uri contactData = data.getData();
        // 查询就是输入URI等参数,其中URI是必须的,其他是可选的,如果系统能找到URI对应的ContentProvider将返回一个Cursor对象.
        Cursor cursor = managedQuery(contactData, null, null, null, null);
        if(cursor == null) return;
        cursor.moveToFirst();
        if (!cursor.isFirst()) return;
        // 获得DATA表中的名字
        username = cursor.getString(cursor
                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        // 条件为联系人ID
        String contactId = cursor.getString(cursor
                .getColumnIndex(ContactsContract.Contacts._ID));
        // 获得DATA表中的电话号码，条件为联系人ID,因为手机号码可能会有多个
        Cursor phone = reContentResolverol.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                        + contactId, null, null);
        while (phone.moveToNext()) {
            usernumber = phone
                    .getString(phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            etName.setText(username);
            etPhone.setText(usernumber.replace(" ",""));
        }
    }

    @Override
    public void addAddressFailed(String msg) {
        showToast(msg);
    }

    @Override
    public void audateAddressSuccess(UpdateAddressBean.DataBean bean) {
        finish();
    }

    @Override
    public void getAddressList(AddressListBean.DataBean dataBean) {
        ArrayList<City> arrayList = new ArrayList<>();
        for(AddressListBean.DataBean.ShItemsBean bean:dataBean.getSh_items()){
            City city = new City();
            city.setGrade(mPositon);
            city.setId(bean.getSh_id());
            city.setName(bean.getSh_name());
//            city.setIsMunicipality(bean.);
            arrayList.add(city);
        }
        dialog.setCities(arrayList);
    }

}
